﻿<!DOCTYPE html>
<html>
<head>
    <title>JS Objects Exercise 6</title>
    <link href="styles/js-console.css" rel="stylesheet" />
</head>
<body>
    <h1>Function that groups an array of persons by age, first or last name.</h1>
    <div id="js-console"></div>
    <script src="scripts/js-console.js"></script>
    <script>
        function group(pers, attr) {
            var persDict = {};
            for (var person in pers)
            {
                // get person's attribute (first name for example)
                // and add it as propery in persDict with value = person object.
                if (persDict[pers[person][attr]] == undefined)
                {
                    persDict[pers[person][attr]] = [];
                }
                persDict[pers[person][attr]].push(pers[person]);
            }

            return persDict;
        }

        function personToString(person)
        {
            return "Name: " + person.firstname + " " + person.lastname + " age: " + person.age;
        }

        function personsToString(pers)
        {
            var str = "";
            for (var idx = 0; idx < pers.length; idx++)
            {
                str += personToString(pers[idx]);
                if (idx != pers.length - 1)
                {
                    str += ", ";
                }
            }
            return str;
        }

        function printPerson(person)
        {
            jsConsole.writeLine(personToString(person));
        }

        function printPersons(pers) {
            jsConsole.writeLine(personsToString(pers));
        }

        function printGroup(groupArr)
        {
            for (var group in groupArr)
            {
                jsConsole.writeLine(group + " = " + personsToString(groupArr[group]));
            }
        }

        var persons = [
          { firstname: "Gosho", lastname: "Petrov", age: 32 },
          { firstname: "Gosho", lastname: "Hristov", age: 21 },
          { firstname: "Ceco", lastname: "Elvisa", age: 29 },
          { firstname: "Joro", lastname: "Hubaveca", age: 21 },
          { firstname: "Bay", lastname: "Ivan", age: 81 }
        ];

        var groupedByFname = group(persons, "firstname");
        var groupedByAge = group(persons, "age");

        jsConsole.writeLine("Grouped by first name:");
        printGroup(groupedByFname);
        jsConsole.writeLine("Grouped by age:");
        printGroup(groupedByAge);

        jsConsole.writeLine("Print Gosho directly:");
        printPersons(groupedByFname.Gosho);

    </script>
</body>
</html>
